<?php

namespace App\Libs;

use App\Models\SiteConfig;
use App\Models\MessageSms;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Log;
use App\Libs\HttpCurlLibrary;

//腾讯sdk
use Qcloud\Sms\SmsSingleSender;


class SmsLibrary
{
   
    //站点配置类型
    CONST SITE_CONFIG = [
        'UPLOAD'=>1,//附件上传
        'SMS'=>2,//短信
    ];

    CONST BUSINESS_TYPE = [
         'PROMOTION' => 1,//推广
         'VERIFICATION_CODE' => 10,//验证码
         'NOTIFICATION' => 20,//通知
         'HOUSE' => 30,//房源
         'HOUSE_NEGOTIATE' => 31,//房源磋商
    ];

    public static function sms($mobile,  $business_type = self::BUSINESS_TYPE['VERIFICATION_CODE'], $data = [])
    {
       //die("sdfs");
        Log::info('*******************发送短信**********************');
        if($business_type == self::BUSINESS_TYPE['VERIFICATION_CODE']){
            $action = 'verification_code';
        }
        dd(App::environment());
        if(App::environment() != 'production'){
            if($business_type == self::BUSINESS_TYPE['VERIFICATION_CODE']){
                $code = '111111';
                cache()->set("sms_".$action.'_'.$mobile, $code, 300);   
            }
            return response()->json(['code'=>'200', 'message'=>'发送成功', 'data'=>[]]);
        }else{
            try{
                $message_content = '';
                if($business_type == self::BUSINESS_TYPE['VERIFICATION_CODE']){
                    $code = rand(1000,9999);
                    $message_content = "您的验证码为：{$code}，请于30分钟内正确输入";
                    $data['code'] = $code;
                    $res = self::tencentSingleSenderSms($mobile, $business_type, $message_content, $data);
                }else{
                    $res = self::lianluSms($mobile, $business_type, $message_content, $data);
                }
                $time = time();
                $data = [
                    'receiver'=> $mobile,
                    'content'=> $message_content,
                    'channel'=> 1,
                    'business_type'=> $business_type,
                    'create_time'=> $time,
                    'update_time'=> $time,
                ];
                $message_id = MessageSms::insertGetId($data);
                if($res['status'] == 1){
                    if($business_type == self::BUSINESS_TYPE['VERIFICATION_CODE']){
                        cache()->set("sms_".$action.'_'.$mobile, $code, 300);
                    }
                }  
                MessageSms::where(['id'=>$message_id])->update(['status'=>$res['status'],'messageid'=> $res['message_id']]);
            }catch(\Exception $e){
                Log::error($mobile.'短信发送失败：'.$e->getMessage());
                return response()->json(['code'=>'0', 'message'=>'发送失败', 'data'=>[]]);
            }
            return response()->json(['code'=>'200', 'message'=>'发送成功', 'data'=>[]]);
        }
    }

    /**
     * 腾讯云模板单手机号发送短信
     */
    public static function tencentSingleSenderSms($mobile, $business_type, $message_content, $data = [])
    {
        // 指定模板ID单发短信
        try {
            $appid = '1400930691';
            $appkey = '21dae1e63ae9aaf569a24d91ab61f571';
            $smsSign = '手拉手';
            $templateId = 2239843;
            $ssender = new SmsSingleSender($appid, $appkey);
            $result = $ssender->sendWithParam("86", $mobile, $templateId, [$data['code'], 1], $smsSign, "", "");  // 签名参数未提供或者为空时，会使用默认签名发送短信
            //$rsp = json_decode($result);
            Log::info('腾讯短信发送'.$result);
            $result = json_decode($result, true);
            if(isset($result['result']) && $result['errmsg'] == 'OK'){
                return [
                    'status'=> 1,
                    'message_id'=> $result['sid']
                ];
            }else{
                return [
                    'status'=> 2,
                    'message_id'=> ''
                ];
            }
        } catch(\Exception $e) {
            Log::error('上传失败:'.$e->getMessage());
        }
    }


    /**
     * 阿里云发送短信
     *
     */
    public static function aliYunSms($mobile, $business_type, $message_content, $data = [])
    {
        $template_id = '';
        $sign_name = ''; 
        $config=config("easysms");//阿里云
        $info = SiteConfig::getInfo(self::SITE_CONFIG['SMS']);
        if(empty($info)){
            return response()->json(['code'=>'0', 'message'=>'请配置短信信息', 'data'=>[]]);
        }
        $content = json_decode($info->content,true);
        if(empty($content) || empty($content['aliyun']['access_key_id'])) return response()->json(['code'=>'0', 'message'=>'请配置短信信息', 'data'=>[]]);
        
        if($content['storage_type'] == 1){
            $sms_type = 'aliyun';
        }else{
            return response()->json(['code'=>'0', 'message'=>'短信配置错误', 'data'=>[]]);
        }
        $config['default']['gateways'] = [$sms_type];
        $config['gateways'][$sms_type] = [
            'access_key_id' => $content[$sms_type]['access_key_id'],
            'access_key_secret' => $content[$sms_type]['access_key_secret'],
            'sign_name' => $sign_name,
        ];
        $easySms = new \Overtrue\EasySms\EasySms($config);
        
        $res = $easySms->send($mobile, [
            'content'=> $message_content,
            'template' => $template_id,
            'data' => $data
        ]);
        
    }

    /**
     * 发送联麓平台短信
     *
     */
    public function lianluSms($mobile, $business_type, $data=[])
    {
        if($business_type == self::BUSINESS_TYPE['HOUSE_NEGOTIATE']){
            $commuinty_name = $data['commuinty_name'];
            $title = $data['title'];
            $admin_name = $data['admin_name'];
            $time = $data['time'];
        }
		
        // 参数
        $params = [
            'MchId' => '1050747', // 企业ID
            'AppId' => '10011723797564552', // appid
            'Version' => '1.2.0',
            'Type' => '1',
            'PhoneNumberSet' => $mobile,
            'SignName' => '【手拉手房产网】',
            'SessionContext' => "您维护的{$commuinty_name}编号为：{$title}的房源由房小二{$admin_name}预约{$time}进行磋商，请悉知！",
            'TimeStamp' => $this->getMillisecond(),
            'SignType'=> 'MD5'
        ];

        // 签名
        $sign = $this->MakeSign($params, '2c597e1a68e04f24b7b79a57f8807795');
        $params['Signature'] = $sign;

        $response = HttpCurlLibrary::request(json_encode($params), 'https://apis.shlianlu.com/sms/trade/normal/send');
        // 日记记录
        //trace(['send' => $params, 'result' => $response], 'info');
        return $response;
    }

	
    /**
     * 获取毫秒级别的时间戳
     */
    public static function getMillisecond()
    {
        //获取毫秒的时间戳
        $time = explode ( " ", microtime () );
        $time = $time[1] . ($time[0] * 1000);
        $time2 = explode( ".", $time );
        return $time2[0];
    }

    /**
     * 生成签名
     * @param $data
     * @param $appKey
     * @return string
     */
    public function MakeSign($data, $appKey)
    {
        //签名步骤一：按字典序排序参数
        ksort($data);
        $string = $this->ToUrlParams($data);
        //签名步骤二：在string后加入KEY
        $string = $string . "&key=".$appKey;
        //签名步骤三：MD5加密或者HMAC-SHA256
        $string = md5($string);

        //签名步骤四：所有字符转为大写
        return strtoupper($string);
    }

    /**
     * 格式化参数格式化成url参数
     */
    public function ToUrlParams($data)
    {
        $buff = "";
        $noSignKey = array("Signature", "ContextParamSet", "TemplateParamSet", "SessionContextSet", "PhoneNumberSet", "SessionContext", "PhoneList", "phoneSet");
        foreach ($data as $k => $v)
        {
            if(!in_array($k, $noSignKey) && $v != "" && !is_array($v)){
                $buff .= $k . "=" . $v . "&";
            }
        }
        return trim($buff, "&");
    }

    
}
